package com.second.app.excutor;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author GYZ
 * @Date 2023/10/18
 * <pre>
 *
 * </pre>
 */
@Slf4j
public class Demo {
    public static void main(String[] args) {
        int numStores = 50;
        ExecutorService executor = Executors.newFixedThreadPool(10); // 可以根据系统资源和性能需求选择线程池大小
        List<Future<StoreResult>> storeResults = new ArrayList<>();

        for (int storeId = 1; storeId <= numStores; storeId++) {
            int finalStoreId = storeId;
            Future<StoreResult> future = executor.submit(() -> {
                try {
                    return pushSalesData(finalStoreId);
                } catch (Exception e) {
                    // 处理异常，这里可以记录日志或采取其他适当的措施
                    System.err.println("门店 " + finalStoreId + " 推送数据异常: " + e.getMessage());
                    return new StoreResult(finalStoreId, false, e.getMessage());
                }
            });
            storeResults.add(future);
        }

        // 关闭线程池，不再接受新任务
        executor.shutdown();

        try {
            // 等待所有门店任务完成，设置一个合理的超时时间
            if (!executor.awaitTermination(1, TimeUnit.HOURS)) {
                // 可以选择采取适当的措施，例如强制关闭线程池
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 处理中断异常
            e.printStackTrace();
        }

        // 获取每家门店的执行结果
        for (Future<StoreResult> future : storeResults) {
            try {
                StoreResult result = future.get();
                System.out.println("门店 " + result.getStoreId() + " 执行结果: " + result.isSuccessful());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    // 模拟门店销售数据推送任务
    private static StoreResult pushSalesData(int storeId) {
        // 在这里编写具体的门店销售数据推送逻辑
        // 如果成功完成，返回StoreResult对象；如果出现异常，返回带有异常信息的StoreResult对象
        // 示例：模拟成功
        return new StoreResult(storeId, true, "数据推送成功");
    }
}

class StoreResult {
    private int storeId;
    private boolean successful;
    private String message;

    public StoreResult(int storeId, boolean successful, String message) {
        this.storeId = storeId;
        this.successful = successful;
        this.message = message;
    }

    public int getStoreId() {
        return storeId;
    }

    public boolean isSuccessful() {
        return successful;
    }

    public String getMessage() {
        return message;
    }
}
